package com.panshi.controller;

import com.panshi.entity.SysAdminApi;
import com.panshi.service.SysClientService;
import com.panshi.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class AdminLoginController {

    @Autowired
    private SysClientService sysClientService;


    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String toLogin(HttpServletRequest request, Model model, HttpSession session){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("账号密码--------------"+username+" "+MD5Util.getMD5Str(password));
        //获得当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据  //生成token
        UsernamePasswordToken token = new UsernamePasswordToken(username,MD5Util.getMD5Str(password));
        token.setRememberMe(true);  //开启记住我功能
        try {
            subject.login(token);   //执行登录方法，如果没有异常就OK 完成登录
            System.out.println("登录成功----------------》");
            SysAdminApi adminApi = (SysAdminApi)subject.getPrincipal();
            session.setAttribute("adminApi",adminApi);
            //model.addAttribute("adminApi",adminApi);
            return "index";
        }catch (UnknownAccountException e){ //用户名不存在
            model.addAttribute("msg","请输入正确账号！");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }

    //未授权用户
    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未授权无法访问此页面,请联系管理员";
    }

}
